<!--
  * 菜单 表单弹窗
-->
<template>
  <a-drawer
    :body-style="{ paddingBottom: '80px' }"
    :maskClosable="true"
    :title="form.id ? '编辑' : '添加'"
    :visible="visible"
    :width="550"
    @close="onClose"
  >
    <a-form ref="formRef" :labelCol="{ span: labelColSpan }" :labelWrap="true" :model="form" :rules="rules">
      <a-form-item label="菜单类型" name="type">
        <a-radio-group v-model:value="form.type" button-style="solid">
          <a-radio-button v-for="item in MENU_TYPE_ENUM" :key="item.value" :value="item.value">
            {{ item.desc }}
          </a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="上级目录">
        <MenuTreeSelect ref="parentMenuTreeSelect" v-model:value="form.parentId" />
      </a-form-item>

      <a-form-item label="资源名称" name="name">
          <a-input v-model:value="form.name" placeholder="请输入资源名称" />
        </a-form-item>

      <!--      目录 菜单 start   -->
      <template v-if="form.type == MENU_TYPE_ENUM.MENU.value">
        <a-form-item label="资源图标" name="icon">
          <IconSelect @updateIcon="selectIcon">
            <template #iconSelect>
              <a-input v-model:value="form.iconPath" placeholder="请输入菜单图标" style="width: 200px" />
              <component :is="$antIcons[form.iconPath]" class="smart-margin-left15" style="font-size: 20px" />
            </template>
          </IconSelect>
        </a-form-item>
      </template>
        <a-form-item  :label="form.type === MENU_TYPE_ENUM.MENU.value ? '路由地址' : '控制标志' " name="path">
          <a-input v-model:value="form.path" placeholder="请输入路由地址" />
        </a-form-item>
        <a-form-item label="排序" name="showOrder">
          <a-input-number v-model:value="form.showOrder" :min="0" placeholder="请输入排序" style="width: 100%" />
          <h6 style="color: #ababab">值越小越靠前</h6>
        </a-form-item>
      <template v-if="form.type == MENU_TYPE_ENUM.MENU.value">
          <a-form-item :label="form.frameFlag==='Y' ? '外链地址' : '组件地址' " name="component">
            <a-input v-model:value="form.component" placeholder="请输入地址(组件地址默认带有开头/@/views)" />
          </a-form-item>
          <a-form-item v-if="form.type == MENU_TYPE_ENUM.MENU.value" label="是否外链" name="frameFlag">
          <a-switch v-model:checked="form.frameFlag" checked-children="是外链" checkedValue="Y" un-checked-children="不是外链"  unCheckedValue="N"  />
          </a-form-item>
      </template>
        <a-form-item v-if="form.type == MENU_TYPE_ENUM.MENU.value" label="是否显示" name="showFlag">
          <a-switch v-model:checked="form.showFlag" checked-children="显示" checkedValue="Y" un-checked-children="不显示"  unCheckedValue="N"  />
        </a-form-item>
      <!--      目录 菜单 end   -->
      <a-form-item label="禁用状态" name="state">
          <a-switch v-model:checked="form.state" checked-children="启用" checkedValue="Y"  un-checked-children="禁用" unCheckedValue="N" />
        </a-form-item>
    </a-form>
    <div class="footer">
      <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
      <a-button style="margin-right: 8px" type="primary" @click="onSubmit(false)">提交 </a-button>
      <a-button v-if="!form.id" type="primary" @click="onSubmit(true)">提交并添加下一个 </a-button>
    </div>
  </a-drawer>
</template>
<script setup lang="ts">
  import { message } from 'ant-design-vue';
  import _ from 'lodash';
  import { computed, nextTick, reactive, ref, watch } from 'vue';
  import MenuTreeSelect from './menu-tree-select.vue';
  import { menuApi } from '/@/api/system/menu/menu-api';
  import IconSelect from '/@/components/framework/icon-select/index.vue';
  import { MENU_DEFAULT_PARENT_ID, MENU_TYPE_ENUM } from '/@/constants/system/menu-const';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { SmartLoading } from '/@/components/framework/smart-loading';

  // ----------------------- 以下是字段定义 emits props ------------------------
  // emit
  const emit = defineEmits(['reloadList']);

  // ----------------------- 展开、隐藏编辑窗口 ------------------------

  // 是否展示抽屉
  const visible = ref(false);

  const contextMenuTreeSelect = ref();
  const parentMenuTreeSelect = ref();

  //展开编辑窗口
  async function showDrawer(rowData) {
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
      if (form.parentId === MENU_DEFAULT_PARENT_ID) {
        form.parentId = null;
      }
    }
    visible.value = true;
    refreshParentAndContext();
  }

  function refreshParentAndContext() {
    nextTick(() => {
      if (contextMenuTreeSelect.value) {
        contextMenuTreeSelect.value.queryMenuTree();
      }
      if (parentMenuTreeSelect.value) {
        parentMenuTreeSelect.value.queryMenuTree();
      }
    });
  }

  // 隐藏窗口
  function onClose() {
    Object.assign(form, formDefault);
    formRef.value.resetFields();
    visible.value = false;
  }

  // ----------------------- 预加载数据 ------------------------

  // ----------------------- form表单相关操作 ------------------------

  const formRef = ref();
  const formDefault = {
    id: undefined,
    name: undefined,
    type: MENU_TYPE_ENUM.MENU.value,
    iconPath: undefined,
    parentId: undefined,
    path: undefined,
    showOrder: undefined,
    state: "Y",
    showFlag: "Y",
    component: undefined,
    frameFlag: "N",
  };
  let form = reactive({ ...formDefault });

  function continueResetForm() {
    refreshParentAndContext();
    const menuType = form.type;
    const parentId = form.parentId;
    Object.assign(form, formDefault);
    formRef.value.resetFields();
    form.type = menuType;
    form.parentId = parentId;
  }

  const rules = {
    type: [{ required: true, message: '菜单类型不能为空' }],
    name: [
      { required: true, message: '菜单名称不能为空' },
      { max: 20, message: '菜单名称不能大于20个字符', trigger: 'blur' },
    ],
    path: [
      { required: true, message: '路由地址不能为空' },
      { max: 100, message: '路由地址不能大于100个字符', trigger: 'blur' },
    ],
  };

  function validateForm(formRef) {
    return new Promise((resolve) => {
      formRef
        .validate()
        .then(() => {
          resolve(true);
        })
        .catch(() => {
          resolve(false);
        });
    });
  }

  const onSubmit = async (continueFlag) => {
    let validateFormRes = await validateForm(formRef.value);
    if (!validateFormRes) {
      message.error('参数验证错误，请仔细填写表单数据!');
      return;
    }
    SmartLoading.show();
    try {
      let params = _.cloneDeep(form);
      // 若无父级ID 默认设置为0
      if (!params.parentId) {
        params.parentId = '0';
      }

      let res=await menuApi.saveMenu(params);
      if(res.success)
        message.success(res.message);
      else
        message.error(res.message);
      if (continueFlag) {
        continueResetForm();
      } else {
        onClose();
      }
      emit('reloadList');
    } catch (error) {
      smartSentry.captureError(error);
    } finally {
      SmartLoading.hide();
    }
  };

  function selectIcon(icon) {
    form.iconPath = icon;
  }

  // ----------------------- 以下是暴露的方法内容 ------------------------
  defineExpose({
    showDrawer,
  });
</script>
<style lang="less" scoped>
  .footer {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e9e9e9;
    padding: 10px 16px;
    background: #fff;
    text-align: left;
    z-index: 1;
  }
</style>
